#coding=utf-8
# Copyright 2011-2012 Maxim Petrov <maximpetrov@yahoo.com>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 3 or any later version.

from modal_window import ModalWindow
from controls import Label
import curses

class MessageWindow(ModalWindow):
    """Modal window with error message"""

    # Redefine ModalWindow constants
    _SHOULD_ENLARGE = False
    _PREFERRED_MIN_HEIGHT = 5
    _MIN_HEIGHT = 3
    _message_visible = True
    _EXIT_BUTTON = u'Ok'

    def __init__(self, message):
        """
        Constructor.

        Keywords arguments:
            message - message to show
        """
        self.__message_label = Label(None, lambda w, h: (2, 2, None, None), message)
        self._controls = [(self.__message_label, False)]
        self._PREFERRED_MIN_WIDTH = len(message) + 4
        self._MIN_WIDTH = len(message) + 2


    def handle_keypress(self, ch, uni):
        """
        Function handle keypress.

        Keywords arguments:
            ch - pressed key
            uni - True if ch is Unicode char, False otherwise

        Return value:
            Return dictionary contains pressed button if this keypress results
            closing window, otherwise return None
        """

        result = ModalWindow.handle_keypress(self, ch, uni)
        if result is not None:
            return result
        elif ch == ord('\n'):
            return {u'button': self._EXIT_BUTTON}


class ErrorWindow(MessageWindow):
    """ErrorWindow (MessageWindow with title "Error")"""

    _title = _(u'Error')


class KeycodeWindow(MessageWindow):
    """Window with message that wait for any keypress (except Esc) and return code of pressed key"""

    _title = _(u'Keycode')
    _EXIT_BUTTON = u'Cancel'

    def handle_keypress(self, ch, uni):
        """
        Function handle keypress.

        Keywords arguments:
            ch - pressed key
            uni - True if ch is Unicode char, False otherwise

        Return value:
            Return dictionary contains pressed button if this keypress results
            closing window, otherwise return None
        """

        result = ModalWindow.handle_keypress(self, ch, uni)
        if result is not None:
            return result
        elif not uni and ch > 0 and ch != curses.KEY_RESIZE:
            return {u'button': u'Ok', u'code': ch}